package com.example.demo.controller;

import com.example.demo.Uilt.Uilt;
import com.example.demo.repository.PointRepository;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Autowired
    private PointRepository pointRepository;

    private List<WebSocketSession> sessionsRas = new CopyOnWriteArrayList<>();
    private List<WebSocketSession> sessionsVec = new CopyOnWriteArrayList<>();
    private Gson gson = new GsonBuilder().setLenient().create();


    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(new WebSocketRas(), "/my-websocket-ras").setAllowedOrigins("*");
        registry.addHandler(new WebSocketVec(), "/my-websocket-vec").setAllowedOrigins("*");
    }

    private class WebSocketVec extends TextWebSocketHandler {

        @Override
        protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
            Map<String, List<Double>> map = gson.fromJson(message.getPayload(), Map.class);

            List<String[]> points = new ArrayList<>();
            // 使用foreach循环遍历Map
            for (Map.Entry<String, List<Double>> entry : map.entrySet()) {
                String key = entry.getKey(); // 获取Map中的key
                List<Double> valueList = entry.getValue(); // 获取Map中的value

                double number = valueList.get(0);
                DecimalFormat df = new DecimalFormat("#.###############");
                String output = df.format(number);


                String wktPoint = "POINT ZM(" + output + " " + valueList.get(1).toString() + " 1 1)";
                System.out.println(wktPoint);
                Boolean aBoolean = pointRepository.updateGeom(key, wktPoint);

                if (aBoolean) {
                    points.add(new String[]{key, String.valueOf(valueList.get(2)), String.valueOf(valueList.get(3))});
                }
            }

            // 将Java对象序列化为JSON字符串

            String json = gson.toJson(points);
            for (WebSocketSession s : sessionsVec) {
                if (s.isOpen()) {
                    if (points.size() > 0) {
                        s.sendMessage(new TextMessage(json));
                    }
                } else {
                    sessionsVec.remove(s);
                }
            }
        }

        @Override
        public void afterConnectionEstablished(WebSocketSession session) throws Exception {
            sessionsVec.add(session);
        }

        @Override
        public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
            sessionsVec.remove(session);
        }
    }

    private class WebSocketRas extends TextWebSocketHandler {

        @Override
        protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
            Map<String, List<Double>> map = gson.fromJson(message.getPayload(), Map.class);

            List<Double[]> points = new ArrayList<>();
            // 使用foreach循环遍历Map
            for (Map.Entry<String, List<Double>> entry : map.entrySet()) {
                String key = entry.getKey(); // 获取Map中的key
                List<Double> valueList = entry.getValue(); // 获取Map中的value

                double number = valueList.get(0);
                DecimalFormat df = new DecimalFormat("#.###############");
                String output = df.format(number);


                String wktPoint = "POINT ZM(" + output + " " + valueList.get(1).toString() + " 1 1)";
                System.out.println(wktPoint);
                Boolean aBoolean = pointRepository.updateGeom(key, wktPoint);

                if (aBoolean) {
                    // 删除16到22级的tms瓦片
                    for (int i = 16; i <= 22; i++) {
                        Uilt.deleteTmsFile(valueList.get(2), valueList.get(3), i, "C:\\Users\\Administrator\\AppData\\Local\\Temp\\geowebcache\\zhouweijun_ps_point_n", "EPSG_900913");
                        Uilt.deleteTmsFile(valueList.get(4), valueList.get(5), i, "C:\\Users\\Administrator\\AppData\\Local\\Temp\\geowebcache\\zhouweijun_ps_point_n", "EPSG_900913");
                    }
                    points.add(new Double[]{valueList.get(2), valueList.get(3)});
                    points.add(new Double[]{valueList.get(4), valueList.get(5)});
                }
            }

            // 将Java对象序列化为JSON字符串

            String json = gson.toJson(points);
            for (WebSocketSession s : sessionsRas) {
                if (s.isOpen()) {
                    if (points.size() > 0) {
                        s.sendMessage(new TextMessage(json));
                    }
                } else {
                    sessionsRas.remove(s);
                }
            }
        }

        @Override
        public void afterConnectionEstablished(WebSocketSession session) throws Exception {
            sessionsRas.add(session);
        }

        @Override
        public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
            sessionsRas.remove(session);
        }
    }
}
//// 创建WebSocket连接
//    var socket = new WebSocket("ws://localhost:8044/my-websocket");
//
//// 当连接打开时，向服务器发送一条消息
//         socket.onopen = function(event) {
//        socket.send("Hello, server!");
//        };
//
//// 当接收到服务器发来的消息时，进行处理
//        socket.onmessage = function(event) {
//        console.log("Received message from server: " + event.data);
//        };
//
//// 当连接关闭时，进行清理工作
//        socket.onclose = function(event) {
//        console.log("Connection closed.");
//        };

//发送消息
//socket.send()
